using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CR.Application.DTOs;
using CR.Application.Interfaces;
using CR.ErrorCode;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace CR.API.Controllers
{
    /// <summary>
    /// 溯源管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class TraceabilityController : ControllerBase
    {
        private readonly ITraceabilityService _traceabilityService;
        private readonly ILogger<TraceabilityController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="traceabilityService">溯源管理服务</param>
        /// <param name="logger">日志记录器</param>
        public TraceabilityController(ITraceabilityService traceabilityService, ILogger<TraceabilityController> logger)
        {
            _traceabilityService = traceabilityService;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有溯源管理记录
        /// </summary>
        /// <returns>溯源管理记录列表</returns>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<ApiResult<IEnumerable<TraceabilityManagementDTO>>>> GetAll()
        {
            try
            {
                var result = await _traceabilityService.GetAllTraceabilityAsync();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有溯源管理记录时出错");
                return StatusCode(500, ApiResult<IEnumerable<TraceabilityManagementDTO>>.Fail(ApiEnums.SystemError, "获取溯源管理记录失败"));
            }
        }

        /// <summary>
        /// 根据ID获取溯源管理记录
        /// </summary>
        /// <param name="id">溯源管理ID</param>
        /// <returns>溯源管理记录</returns>
        [HttpGet("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<ApiResult<TraceabilityManagementDTO>>> GetById(int id)
        {
            try
            {
                var result = await _traceabilityService.GetTraceabilityByIdAsync(id);
                if (result.Code == ApiEnums.NotFound)
                {
                    return NotFound(result);
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据ID获取溯源管理记录时出错，ID: {Id}", id);
                return StatusCode(500, ApiResult<TraceabilityManagementDTO>.Fail(ApiEnums.SystemError, "获取溯源管理记录失败"));
            }
        }

        /// <summary>
        /// 根据溯源码获取溯源管理记录
        /// </summary>
        /// <param name="code">溯源码</param>
        /// <returns>溯源管理记录</returns>
        [HttpGet("code/{code}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<ApiResult<TraceabilityManagementDTO>>> GetByCode(string code)
        {
            try
            {
                var result = await _traceabilityService.GetTraceabilityByCodeAsync(code);
                if (result.Code == ApiEnums.NotFound)
                {
                    return NotFound(result);
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据溯源码获取溯源管理记录时出错，溯源码: {Code}", code);
                return StatusCode(500, ApiResult<TraceabilityManagementDTO>.Fail(ApiEnums.SystemError, "获取溯源管理记录失败"));
            }
        }

        /// <summary>
        /// 创建溯源管理记录
        /// </summary>
        /// <param name="createDto">创建DTO</param>
        /// <returns>创建后的溯源管理记录</returns>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<ApiResult<TraceabilityManagementDTO>>> Create([FromBody] TraceabilityCreateDTO createDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _traceabilityService.CreateTraceabilityAsync(createDto);
                
                if (result.Code == ApiEnums.Success)
                {
                    return CreatedAtAction(nameof(GetById), new { id = result.Data.Id }, result);
                }
                else if (result.Code == ApiEnums.BadRequest)
                {
                    return BadRequest(result);
                }
                
                return StatusCode(500, result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建溯源管理记录时出错");
                return StatusCode(500, ApiResult<TraceabilityManagementDTO>.Fail(ApiEnums.SystemError, "创建溯源管理记录失败"));
            }
        }

        /// <summary>
        /// 更新溯源管理记录
        /// </summary>
        /// <param name="id">溯源管理ID</param>
        /// <param name="updateDto">更新DTO</param>
        /// <returns>更新后的溯源管理记录</returns>
        [HttpPut("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<ApiResult<TraceabilityManagementDTO>>> Update(int id, [FromBody] TraceabilityUpdateDTO updateDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                if (id != updateDto.Id)
                {
                    return BadRequest(ApiResult<TraceabilityManagementDTO>.Fail(ApiEnums.BadRequest, "ID不匹配"));
                }

                var result = await _traceabilityService.UpdateTraceabilityAsync(id, updateDto);
                
                if (result.Code == ApiEnums.NotFound)
                {
                    return NotFound(result);
                }
                else if (result.Code == ApiEnums.BadRequest)
                {
                    return BadRequest(result);
                }
                
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新溯源管理记录时出错，ID: {Id}", id);
                return StatusCode(500, ApiResult<TraceabilityManagementDTO>.Fail(ApiEnums.SystemError, "更新溯源管理记录失败"));
            }
        }

        /// <summary>
        /// 删除溯源管理记录
        /// </summary>
        /// <param name="id">溯源管理ID</param>
        /// <returns>操作结果</returns>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<ApiResult>> Delete(int id)
        {
            try
            {
                var result = await _traceabilityService.DeleteTraceabilityAsync(id);
                
                if (result.Code == ApiEnums.NotFound)
                {
                    return NotFound(result);
                }
                
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除溯源管理记录时出错，ID: {Id}", id);
                return StatusCode(500, ApiResult.Fail(ApiEnums.SystemError, "删除溯源管理记录失败"));
            }
        }

        /// <summary>
        /// 批量删除溯源管理记录
        /// </summary>
        /// <param name="ids">ID列表</param>
        /// <returns>操作结果</returns>
        [HttpPost("batch-delete")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<ApiResult>> BatchDelete([FromBody] List<int> ids)
        {
            try
            {
                if (ids == null || ids.Count == 0)
                {
                    return BadRequest(ApiResult.Fail(ApiEnums.BadRequest, "未提供要删除的ID"));
                }

                var result = await _traceabilityService.BatchDeleteTraceabilityAsync(ids);
                
                if (result.Code == ApiEnums.BadRequest)
                {
                    return BadRequest(result);
                }
                
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除溯源管理记录时出错");
                return StatusCode(500, ApiResult.Fail(ApiEnums.SystemError, "批量删除溯源管理记录失败"));
            }
        }

        /// <summary>
        /// 分页获取溯源管理记录，支持高级过滤条件
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>分页结果</returns>
        [HttpGet("paged")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<ActionResult<ApiResult<ApiPagin<TraceabilityManagementDTO>>>> GetPaged([FromQuery] TraceabilityQueryDTO query)
        {
            try
            {
                if (query.PageIndex < 1 || query.PageSize < 1)
                {
                    return BadRequest(ApiResult<ApiPagin<TraceabilityManagementDTO>>.Fail(ApiEnums.BadRequest, "页码和每页大小必须大于0"));
                }

                var result = await _traceabilityService.GetPagedTraceabilityAsync(query);
                
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分页获取溯源管理记录时出错");
                return StatusCode(500, ApiResult<ApiPagin<TraceabilityManagementDTO>>.Fail(ApiEnums.SystemError, "获取溯源管理记录分页数据失败"));
            }
        }
    }
} 